<?php

namespace App\Helpers\Cloud;

use Exception;
use Qiniu\Auth;
use Qiniu\Config;
use Qiniu\Http\Error;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

/**
 * 七牛云助手类
 *
 * Class QiNiuHelper
 *
 * @package App\Helpers\Cloud
 */
class QiNiuHelper extends BaseCloudHelper
{
	private $accessKey;
	private $secretKey;
	private $bucket;
	private $domain;
	private $uploadUrl;
	private $upToken;
	private $auth;
	private $region; // 区域

	public function __construct()
	{
		parent::__construct();
		$this->init();
	}

	/**
	 * 初始化信息
	 */
	public function init()
	{
		$this->accessKey = config("library.qi_niu.access_key");
		$this->secretKey = config("library.qi_niu.secret_key");
		$this->bucket    = config("library.qi_niu.bucket");
		$this->domain    = config("library.qi_niu.domain");
		$this->uploadUrl = config("library.qi_niu.upload_url");
		$this->region    = config("library.qi_niu.region");
	}

	/**
	 * 执行上传
	 *
	 * @param string $realPath  本地路径
	 * @param string $cdnPath   CDN路径
	 * @param string $extension 扩展名
	 * @return false|string
	 * @throws Exception
	 */
	public function uploadFile(string $realPath, string $cdnPath = '', string $extension = '')
	{
		// 构建鉴权对象
		$this->getUpToken();

		$info = pathinfo($realPath);
		$key  = md5($info['filename']) . '.' . ($extension ?: $info['extension']); // 上传到存储后保存的文件名
		// 拼装CDN路径
		if ($cdnPath) {
			$key = $cdnPath . DIRECTORY_SEPARATOR . $key;
		}

		// 初始化 UploadManager 对象并进行文件的上传
		$uploadMgr = new UploadManager();

		// 调用 UploadManager 的 putFile 方法进行文件的上传
		[$ret, $err] = $uploadMgr->putFile($this->upToken, $key, $realPath);
		if ($err !== null) {
			return false;
		}

		return $ret['key'];
	}

	/**
	 * 删除文件
	 *
	 * @param $file
	 * @return array
	 */
	public function deleteFile($file): array
	{
		$this->getUpToken();

		$bucketManager = new BucketManager($this->auth, new Config());
		$ret           = $bucketManager->delete($this->bucket, $file);
		$delRet        = [
			'code'    => 200,
			'message' => '',
		];
		if ($ret) {
			if (isset($ret[1]) && $ret[1] instanceof Error) {
				$error             = $ret[1];
				$delRet['code']    = $error->code();
				$delRet['message'] = $error->message();
			}
		}

		return $delRet;
	}

	/**
	 * 获取客户端SDK上传需要的token等信息
	 */
	public function getTokenForSDK(): array
	{
		$this->getUpToken();
		return [
			"domain"    => $this->domain,
			"uploadUrl" => $this->uploadUrl,
			"token"     => $this->upToken,
			"region"    => $this->region,
		];
	}

	/**
	 * 获取上传token
	 */
	private function getUpToken()
	{
		$this->auth    = new Auth($this->accessKey, $this->secretKey);
		$this->upToken = $this->auth->uploadToken($this->bucket);
	}
}